package com.kehutong.house.app;

import com.kehutong.common.util.Token;
import com.kehutong.house.entity.Community;
import com.kehutong.house.service.BuildService;
import com.kehutong.house.service.CommunityService;
import com.kehutong.house.service.HouseService;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.util.Objects;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@MvcAction
@ReqMapping("/kht-bin/community")
public class CommunityAction {

    @Inject
    private JdbcSession sqlSession;
    @Inject
    private HouseService houseService;
    @Inject
    private CommunityService communityService;
    @Inject
    private BuildService buildService;

    /**
     * 小程序端使用
     * @param token
     * @param jsonObject
     * @return
     */
    @ReqMapping("/list")
    public Object list(Token token, JSONObject jsonObject) {
        FindArray<Community> find = sqlSession.findArray(Community.class)
                .in(jsonObject, "id")
                .in(jsonObject, "parent_id")
                .like(jsonObject, "name", "viewName", "area_ids", "area_names")
                .eq("deleted", false);
        //如果不是管理员则根据管家过滤小区
        if (!token.getRoles().contains("5")) {
            find.like(jsonObject, "employee_ids");
        }
        List<Community> communityList = find.exe();
        return Result.success(communityList);
    }

    /**
     * 企微端使用
     * @param jsonObject
     * @return
     */
    @ReqMapping("/appList")
    public Object appList(JSONObject jsonObject) {
        return Result.success(communityService.permissionQuery(jsonObject));
    }

    /**
     * 企微端使用
     * @param jsonObject
     * @return
     */
    @ReqMapping("/appMergeQuery")
    public Object appMergeQuery(JSONObject jsonObject) {
        String search = jsonObject.getString("search");
        if(Objects.isEmpty(search)){
            return Result.success();
        }

        // 封装小区查询条件
        JSONObject communityJSON = new JSONObject();
        communityJSON.put("name", search);

        // 封装楼栋查询条件
        JSONObject buildJSON = new JSONObject();
        buildJSON.put("unitName", search);
        buildJSON.put("name", search);

        // 封装房屋查询条件
        JSONObject houseJSON = new JSONObject();
        houseJSON.put("mergeName", search);

        JSONObject result = new JSONObject();
        result.put("communitys", communityService.permissionQuery(communityJSON));
        result.put("builds", buildService.permissionQuery(buildJSON));
        result.put("houses", houseService.permissionQuery(houseJSON));
        return Result.success(result);
    }

    /**
     * 企微端使用
     * @param entity
     * @return
     * @throws Exception
     */
    @ReqMapping("/appGetSteward")
    public Object appGetSteward (Community entity) throws Exception {
        if(Objects.nonNull(entity)){
            JSONObject result = new JSONObject();
            result.put("id", entity.getId());
            result.put("name", entity.getName());

            // 组装管家信息
            List<String> employeeNos = entity.getEmployee_ids();
            List<JSONObject> employees = new ArrayList<>();
            if(Objects.nonEmpty(employeeNos)){
                JSONArray array = communityService.getEmployees(employeeNos);
                array.forEach(item ->{
                    JSONObject temp = (JSONObject) item;

                    JSONObject employee = new JSONObject();
                    employee.put("avatar", temp.getString("avatar"));
                    employee.put("id", temp.getString("id"));
                    employee.put("name", temp.getString("name"));
                    employees.add(employee);
                });
            }
            result.put("employees", employees);

            // 组装所属部门信息
            String parentId = entity.getParent_id();
            JSONObject department = new JSONObject();
            if(Objects.nonEmpty(parentId)){
                Map<String,JSONObject> departmentMap = communityService.getDepartmentMap(Arrays.asList(parentId));
                department.put("id", parentId);
                JSONObject temp = departmentMap.get(parentId);
                String name = "";
                String parent_id = "";
                JSONArray parent_ids = null;
                if(Objects.nonEmpty(temp)){
                    name = temp.getString("name");
                    parent_id = temp.getString("parent_id");
                    parent_ids = temp.getJSONArray("parent_ids");
                }
                department.put("name", name);
                department.put("parent_id", parent_id);
                department.put("parent_ids", parent_ids);
            }
            result.put("department", department);

            return result;
        }

        return Result.error(0, "未获取到小区信息");
    }

    @ReqMapping("/getCommunityTransfer")
    public Object getCommunityTransfer (JSONObject jsonObject) throws Exception {
        return communityService.getCommunityTransfer(jsonObject);
    }

    /**
     * 设置 部门/管家
     * @param jsonObject
     * @return
     */
    @ReqMapping("/setting")
    public Object setting(JSONObject jsonObject){

        String id = jsonObject.getString("id");
        if(Objects.isEmpty(id)){
            return Result.error(0, "小区编号不能为空");
        }

        Community entity = Pool.get(Community.class, id);
        if(Objects.isNull(entity)){
            return Result.error(0, "占未查询到小区信息");
        }

        // 设置部门、管家信息
        String parent_id = jsonObject.getString("parentId");
        JSONArray parent_ids = jsonObject.getJSONArray("parentIds");

        entity.setParent_id(null);
        entity.setParent_ids(null);
        if(Objects.nonEmpty(parent_ids)){
            List<String> parents = JSONObject.parseArray(parent_ids.toString(),String.class);
            entity.setParent_id(parent_id);
            entity.setParent_ids(parents);
        }

        JSONArray employee_ids = jsonObject.getJSONArray("employeeIds");
        entity.setEmployee_ids(null);
        if(Objects.nonEmpty(employee_ids)){
            List<String> employees = JSONObject.parseArray(employee_ids.toString(),String.class);
            entity.setEmployee_ids(employees);
        }

        sqlSession.updateById(entity);

        return Result.success();
    }

    @ReqMapping("/get")
    public Object get(Community item) throws Exception {
        return communityService.get(item);
    }

    @Bean(newInstance=true, copy=true)
    @ReqMapping("/save")
    public Object save(Token token, Community community) throws Exception {
        return communityService.save(token, community);
    }

    @Bean(copy=true, isIgnoreNull = false)
    @ReqMapping("/update")
    public Object update(Token token, Community community, JSONObject jsonObject) throws Exception {
        return communityService.update(token, community, jsonObject);
    }

    @ReqMapping("/delete")
    public Object delete(Community item) {
        return communityService.delete(item);
    }


}
